package com.uhylab.uhuvinetest.pager;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.uhylab.uhuvinetest.R;
import com.uhylab.uhuvinetest.UHApplication;
import com.uhylab.uhuvinetest.activity.UHLogonActivity;
import com.uhylab.uhuvinetest.base.UHBase;
import com.uhylab.uhuvinetest.base.UHBasePager;
import com.uhylab.uhuvinetest.bean.Dataee;
import com.uhylab.uhuvinetest.dao.DaoSingleton;
import com.uhylab.uhuvinetest.dao.UserDataEntity;
import com.uhylab.uhuvinetest.dao.UserDataEntityDao;
import com.uhylab.uhuvinetest.utils.StringUtils;
import com.uhylab.uhuvinetest.utils.VolleySingleton;
import com.uhylab.uhuvinetest.utils.sharedpreutils.SharedPreUtils;
import com.uhylab.uhuvinetest.utils.toastutil.ToastUtil;
import com.zhy.autolayout.AutoRelativeLayout;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by leige07 .
 * Time on 2016/5/13 0013.
 * Description
 */
public class UHUserPager extends UHBasePager implements View.OnClickListener {

    private AutoRelativeLayout user_icon_re, user_name_re, user_tel_re, user_birthday_re, user_six_re, user_wight_re, user_height_re;
    private TextView user_name_exchange, user_tel_exchange, user_birthday_exchange, user_sex_exchange, user_weight_exchange, user_height_exchange;
    private ArrayList<Integer> user_weight_Items = new ArrayList<Integer>();
    private ArrayList<String> user_sex_Items = new ArrayList<String>();
    private ArrayList<Integer> user_height_Items = new ArrayList<Integer>();
    private TimePickerView pvTime;
    private OptionsPickerView user_six;
    private OptionsPickerView user_height;
    private OptionsPickerView user_wight;
    //    private OptionsPickerView user_wight;
    //控制时间范围
    Calendar calendar;
    boolean isLogin;
    private VolleySingleton volleySingleton;
    private String sex, name, tel, date, weight, height;
    private Button exchange;
    private UserDataEntityDao userDataEntityDao;
    private TextView user_login;


    public UHUserPager(Activity activity) {
        super(activity);
        volleySingleton = VolleySingleton.getVolleySingleton(UHApplication.gainContext());
        userDataEntityDao = DaoSingleton.getInstance().getUserDataEntityDao();
        Log.e("TAG", "UHUserPager");
    }

    @Override
    public void initData() {
        super.initData();
        View view = View.inflate(activity, R.layout.basepager_user, null);

        isLogin = SharedPreUtils.getBoolean(activity, "is_Login", false);
        user_icon_re = (AutoRelativeLayout) view.findViewById(R.id.user_icon_re);
        user_name_re = (AutoRelativeLayout) view.findViewById(R.id.user_disease_re);
        user_tel_re = (AutoRelativeLayout) view.findViewById(R.id.user_tel_re);
        user_birthday_re = (AutoRelativeLayout) view.findViewById(R.id.user_birthday_re);
        user_six_re = (AutoRelativeLayout) view.findViewById(R.id.user_six_re);
        user_wight_re = (AutoRelativeLayout) view.findViewById(R.id.user_wight_re);
        user_height_re = (AutoRelativeLayout) view.findViewById(R.id.user_height_re);
        user_name_exchange = (TextView) view.findViewById(R.id.user_disease_exchange);
        user_tel_exchange = (TextView) view.findViewById(R.id.user_tel_exchange);
        user_birthday_exchange = (TextView) view.findViewById(R.id.user_birthday_exchange);
        user_sex_exchange = (TextView) view.findViewById(R.id.user_six_exchange);
        user_weight_exchange = (TextView) view.findViewById(R.id.user_wight_exchange);
        user_height_exchange = (TextView) view.findViewById(R.id.user_height_exchange);
        user_login = (TextView) view.findViewById(R.id.user_login);
        exchange = (Button) view.findViewById(R.id.exchange);

        doBusness();

        fl_child_content.addView(view);
    }

    private void doBusness() {
        user_icon_re.setOnClickListener(this);
        if (isLogin) {
            user_name_re.setOnClickListener(this);
            user_tel_re.setOnClickListener(this);
            user_birthday_re.setOnClickListener(this);
            user_six_re.setOnClickListener(this);
            user_wight_re.setOnClickListener(this);
            user_height_re.setOnClickListener(this);
            exchange.setOnClickListener(this);
            user_login.setVisibility(View.GONE);
        } else {
            user_login.setVisibility(View.VISIBLE);
        }


        //时间选择器
        pvTime = new TimePickerView(activity, TimePickerView.Type.YEAR_MONTH_DAY);
        //选项选择器
        user_wight = new OptionsPickerView(activity);
        user_six = new OptionsPickerView(activity);
        user_height = new OptionsPickerView(activity);
        //控制时间范围
        calendar = Calendar.getInstance();
        for (int i = 30; i < 200; i++) {
            user_weight_Items.add(i);
        }
        for (int i = 100; i < 250; i++) {
            user_height_Items.add(i);
        }
        user_sex_Items.add("男");
        user_sex_Items.add("女");
        user_six.setPicker(user_sex_Items);
        user_six.setCyclic(false);
        user_six.setTitle("请选择性别");
        user_six.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                sex = user_sex_Items.get(options1).toString();
                if (("男").equals(sex)) {
                    user_sex_exchange.setText(sex);
                    sex = "M";
                } else {
                    user_sex_exchange.setText(sex);
                    sex = "F";
                }
                exchange.setVisibility(View.VISIBLE);
            }
        });
        user_height.setPicker(user_height_Items);
        user_height.setLabels("cm");
        user_height.setCyclic(false);
        user_height.setTitle("请选择身高");
        user_height.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                height = user_height_Items.get(options1).toString();
                user_height_exchange.setText(height);
                exchange.setVisibility(View.VISIBLE);
            }
        });
        user_wight.setPicker(user_weight_Items);
        user_wight.setLabels("kg");
        user_wight.setTitle("请选择体重");
        user_wight.setCyclic(false);
        user_wight.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                weight = user_weight_Items.get(options1).toString();
                user_weight_exchange.setText(weight);
                exchange.setVisibility(View.VISIBLE);
            }
        });


        pvTime.setRange(calendar.get(Calendar.YEAR) - 120, calendar.get(Calendar.YEAR));
        pvTime.setTime(new Date());
        pvTime.setCyclic(false);
        pvTime.setCancelable(true);
        //时间选择后回调
        pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date1) {
                date = getTime(date1);
                user_birthday_exchange.setText(date);
                exchange.setVisibility(View.VISIBLE);
            }
        });
    }

    public static String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        user_weight_Items.clear();
        user_sex_Items.clear();
        user_height_Items.clear();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.user_icon_re:
                if (isLogin) {

                } else {
                    Intent intent = new Intent(activity, UHLogonActivity.class);
                    activity.startActivity(intent);
                    // activity.finish();
                }
                break;
            case R.id.user_disease_re:
                showExchangeNameDialog();
                break;
            case R.id.user_tel_re:
                showExchangeTelDialog();
                break;
            case R.id.user_birthday_re:
                pvTime.show();
                break;
            case R.id.user_six_re:
                user_six.show();
                break;
            case R.id.user_wight_re:
                user_wight.show();
                break;
            case R.id.user_height_re:
                user_height.show();
                break;
            case R.id.exchange:
                request();
                break;
        }
    }

    private void showExchangeTelDialog() {
        final Dialog dialog = new Dialog(activity);
        dialog.setContentView(R.layout.smssdk_set_appkey_dialog);

        final EditText etAppKey = (EditText) dialog.findViewById(R.id.et_appkey);
        etAppKey.setHint("请输入手机号");
        View.OnClickListener ocl = new View.OnClickListener() {
            public void onClick(View v) {
                if (v.getId() == R.id.btn_dialog_ok) {
                    if (StringUtils.isPhoneNumberValid(etAppKey.getText().toString().trim())) {
                        tel = etAppKey.getText().toString();
                        user_tel_exchange.setText(tel);
                        dialog.dismiss();
                        exchange.setVisibility(View.VISIBLE);
                    } else {
                        ToastUtil.show(activity, "手机号为空或有误!");
                    }

                } else {
                    dialog.dismiss();
                }
            }
        };
        dialog.findViewById(R.id.btn_dialog_ok).setOnClickListener(ocl);
        dialog.findViewById(R.id.btn_dialog_cancel).setOnClickListener(ocl);
        dialog.setCancelable(false);
        dialog.show();
    }


    private void showExchangeNameDialog() {
        final Dialog dialog = new Dialog(activity);
        dialog.setContentView(R.layout.smssdk_set_appkey_dialog);
        final EditText etAppKey = (EditText) dialog.findViewById(R.id.et_appkey);
        etAppKey.setHint("请输入用户名");
        View.OnClickListener ocl = new View.OnClickListener() {
            public void onClick(View v) {
                if (v.getId() == R.id.btn_dialog_ok) {
                    if (etAppKey.getText().toString().trim() != null) {
                        name = etAppKey.getText().toString();
                        user_name_exchange.setText(name);
                        //setText.set(name);
                        dialog.dismiss();
                        exchange.setVisibility(View.VISIBLE);
                    } else {
                        ToastUtil.show(activity, "用户名为空");
                    }
                } else {
                    dialog.dismiss();

                }
            }
        };
        dialog.findViewById(R.id.btn_dialog_ok).setOnClickListener(ocl);
        dialog.findViewById(R.id.btn_dialog_cancel).setOnClickListener(ocl);
        dialog.setCancelable(false);
        dialog.show();
    }

    @Override
    public void onResume() {
        super.onResume();
        isLogin = SharedPreUtils.getBoolean(activity, "is_Login", false);
        if (isLogin) {
            user_name_re.setOnClickListener(this);
            user_tel_re.setOnClickListener(this);
            user_birthday_re.setOnClickListener(this);
            user_six_re.setOnClickListener(this);
            user_wight_re.setOnClickListener(this);
            user_height_re.setOnClickListener(this);
            exchange.setOnClickListener(this);
            perDetails();
            user_login.setVisibility(View.GONE);
        } else {
            user_login.setVisibility(View.VISIBLE);
        }
    }

    private void perDetails() {
        List<UserDataEntity> userDataEntities = userDataEntityDao.loadAll();
        if (userDataEntities != null && userDataEntities.size() > 0) {
            UserDataEntity userDataEntity = userDataEntities.get(0);
            name = userDataEntity.getName();
            date = userDataEntity.getBirthday();
            weight = userDataEntity.getWeight();
            sex = userDataEntity.getSex();
            height = userDataEntity.getHeight();
            tel = userDataEntity.getTelephone();
            user_name_exchange.setText(name);
            user_tel_exchange.setText(tel);
            user_birthday_exchange.setText(date);
            if (("F").equals(sex)) {
                user_sex_exchange.setText("女");
            } else {
                user_sex_exchange.setText("男");
            }
            user_weight_exchange.setText(weight);
            user_height_exchange.setText(height);
            // setText.set(name);

        }

        StringRequest stringRequest = new StringRequest(Request.Method.POST, UHBase.perDetails, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.e("UHUserCenterFragment", response);
                Gson gson = new Gson();
                Dataee dataee = gson.fromJson(response, Dataee.class);
                Dataee.DataEntity data = dataee.getData();
                if (data != null) {
                    Dataee.DataEntity dataEntity = data;
                    name = (String) dataEntity.getName();
//                    date = (String) dataEntity.getBirthday();
                    weight = Double.toString(dataEntity.getWeight());
                    int se = (int) dataEntity.getSex();
                    if (se == 1) {
                        sex = "M";
                    } else {
                        sex = "F";
                    }


                    height = Double.toString(dataEntity.getHeight());
                    tel = dataEntity.getPhone();
                    user_name_exchange.setText(name);
                    user_tel_exchange.setText(tel);
                    user_birthday_exchange.setText(date);
                    if (("F").equals(sex)) {
                        user_sex_exchange.setText("女");
                    } else {
                        user_sex_exchange.setText("男");
                    }
                    user_weight_exchange.setText(weight);
                    user_height_exchange.setText(height);
                    //setText.set(name);
                    userDataEntityDao.deleteAll();
                    UserDataEntity userDataEntity = new UserDataEntity();
                    userDataEntity.setName(name);
                    userDataEntity.setBirthday(date);
                    userDataEntity.setWeight(weight);
                    userDataEntity.setSex(sex);
                    userDataEntity.setHeight(height);
                    userDataEntity.setTelephone(tel);
                    userDataEntityDao.insertOrReplace(userDataEntity);

                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                //在这里设置需要post的参数
                Map<String, String> params = new HashMap<String, String>();
                String tel = SharedPreUtils.getString(activity, "user_tel", "");
                params.put("telephone", tel);
                return params;
            }
        };
        volleySingleton.addQueue(stringRequest, "stringRequest");
    }

    void request() {
        StringRequest exchangeRe = new StringRequest(Request.Method.POST, UHBase.editDetails, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                exchange.setVisibility(View.GONE);
                Log.e("UHUserCenterFragment", response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                //在这里设置需要post的参数
                Map<String, String> params = new HashMap<String, String>();
                userDataEntityDao.deleteAll();
                UserDataEntity userDataEntity = new UserDataEntity();
                if (tel != null) {
                    params.put("telephone", tel);
                    userDataEntity.setTelephone(tel);
                }
                if (sex != null) {
                    params.put("sex", sex);
                    userDataEntity.setSex(sex);
                }
                if (date != null) {
                    params.put("date", date);
                    userDataEntity.setBirthday(date);
                }
                if (weight != null) {
                    params.put("weight", weight);
                    userDataEntity.setWeight(weight);
                }
                if (height != null) {
                    params.put("height", height);
                    userDataEntity.setHeight(height);
                }
                if (name != null) {
                    params.put("name", name);
                    userDataEntity.setName(name);
                }
                userDataEntityDao.insertOrReplace(userDataEntity);
                return params;
            }
        };
        volleySingleton.addQueue(exchangeRe, "exchangeRe");
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Log.e("TAG", "onAttach");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e("TAG", "onCreate");
    }
}
